<?php

declare(strict_types=1);

namespace App\Services;

use Hyperf\Di\Annotation\Inject;
use App\Exception\ApiException;
use App\Constants\ErrorCode;
use Hyperf\DbConnection\Db;
use Qbhy\HyperfAuth\AuthManager;
use PhpOffice\PhpSpreadsheet\IOFactory;
use App\Model\User;
use App\Model\PointsRanking;
use App\Model\UserVideoViews;
use App\Model\UserFans;
use App\Model\UserOrder;
use App\Model\Platform;
use App\Model\UserPlatform;
use App\Model\DouyinData;
use App\Model\WorkOrder;
use App\Model\AccountRecord;
use App\Model\Goods;
use App\Model\AccessLog;

class UserService extends BaseService
{
    /**
     * @Inject
     * @var AuthManager
     */
    protected $auth;

    /**
     * @var string
     */
    protected $verity_prefix = 'login_verify_code_';

    /**
     * @var int
     */
    protected $verity_exp = 180;

    public function register(array $params)
    {
        $userAccount = User::query()->select('id')->where('account', $params['account'])->where('deleted', 0)->first();
        if($userAccount)
        {
            throw new ApiException(ErrorCode::WARNING, '该账号已存在');
        }
        $userNickname = User::query()->select('id')->where('nickname', $params['nickname'])->where('deleted', 0)->first();
        if($userNickname)
        {
            throw new ApiException(ErrorCode::WARNING, '该昵称已存在');
        }

        $data['level'] = 'B';
        $data['star_currency'] = 1;
        $data['avatar'] = 'https://admin.pubgjiscar.com/upload/41/418333e4c28692716dbdadac38dabd.png';
        $data['account'] = $params['account'];
        $data['salt'] = User::getSalt();
        $data['password'] = md5($params['password'].$data['salt']);
        $data['nickname'] = $params['nickname'];

        $data['status'] = 0;

        User::query()->insert($data);

        return [];
    }

    public function login(array $params)
    {
        // $codeKey = $this->verity_prefix . $params['hash_key'];
        // $redis = redis();
        // if (!$redis->get($codeKey)) {
        //     throw new ApiException(ErrorCode::WARNING, '验证码已过期');
        // } elseif ($redis->get($codeKey) != $params['code']) {
        //     throw new ApiException(ErrorCode::WARNING, '验证码错误');
        // }

        $user = User::query()->select('id','password','salt','level','balance','star_currency','points','avatar','nickname','fullname','birthday','city','gender','signature','wechat','qq','phone','steam','official_server_id','has_partner_privilege_official','test_server_id','has_partner_privilege_test','status','display_icon','last_login_at','created_at')->where('account',$params['account'])->where('deleted', 0)->first();
        if ($user) {
            if($user->status == User::OFF_STATUS){
                throw new ApiException(ErrorCode::WARNING, '请联系管理员开通，QQ：2013330534');
            }

            $check_passwd = md5($params['password'] . $user->salt) == $user->password ? true : false;
            if (!$check_passwd) {
                throw new ApiException(ErrorCode::WARNING, '账号不存在或密码错误');
            }
        } else {
            throw new ApiException(ErrorCode::WARNING, '账号不存在或密码错误');
        }

        $token = $this->auth->login($user);
        $result['user_info'] = $user;
        $result['auth'] = $this->respondWithToken($token);

        User::query()->where('id', $user->id)->update(['last_login_at' => date('Y-m-d H:i:s')]);      //修改最后登录时间

        return $result;
    }

    public function accessLog()
    {
        $ip = get_client_ip();
        AccessLog::query()->insert(['ip' => $ip]);

        return [];
    }

    public function logout()
    {
        if(!$this->auth->check())
        {
            throw new ApiException(ErrorCode::ERR_HTTP_UNAUTHORIZED);
        }

        $this->auth->logout();

        return [];
    }

    /**获取图片验证码
     * @param $params
     * @return array
     */
    public function verifyCode(array $params)
    {
        $config = new \EasySwoole\VerifyCode\Conf();
        $config->setUseCurve($params['curve'] ?? false);
        $config->setUseNoise($params['noise'] ?? false);
        $fontColor = $params['font_color'] ?? "#202223";
        $backColor = $params['back_color'] ?? "#ab9246";
        $config->setFontColor($fontColor);
        $config->setBackColor($backColor);
        $code = new \EasySwoole\VerifyCode\VerifyCode($config);

        //重写验证码
        $imgCode = mt_rand(1000, 9999);
        $result = $code->DrawCode($imgCode);

        //写入缓存 用于其他方法验证 并且设置过期时间
        $redis = redis();
        $redis->set($this->verity_prefix . $result->getCodeHash(), $imgCode, $this->verity_exp);

        //图片
        return ['hash_key' => $result->getCodeHash(), 'verify_img' => $result->getImageBase64()];

    }


    /**
     * 获取令牌数组结构
     *
     * @param $token  令牌 token
     * @return array
     */
    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => time() + config('auth.guards.jwt.ttl'),  // 单位为秒，此时的时间戳加过期时间
        ];
    }

    public function userData()
    {
        $user = auth_user();

        $result = [];

        $result['level'] = $user['level'];

        $lastMonthYear = get_last_month_year();
        $year = $lastMonthYear['year'];
        $month = $lastMonthYear['month'];
        $pointsRanking = PointsRanking::query()->select('rank','points')->where('year', $year)->where('month', $month)->where('user_id', $user['id'])->where('deleted', 0)->first();

        $result['rank'] = $pointsRanking['rank'];
        $result['points'] = $pointsRanking['points'];

        //目前仅存在抖音平台数据
        $result['fans'] = DouyinData::query()->where('user_id', $user['id'])->where('year', $year)->where('month', $month)->where('deleted', 0)->sum('fans_growth');
        $result['volume'] = DouyinData::query()->where('user_id', $user['id'])->where('year', $year)->where('month', $month)->where('deleted', 0)->sum('volume');

        
        //查询上上月数据对比走势
        $result['rank_trend'] = 0;          //默认值，持平
        $result['points_trend'] = 0;
        $result['fans_trend'] = 0;
        $result['volume_trend'] = 0;
        $beforeMonth = strtotime("-2 month"); // 获取上个月的时间戳
        $beforeYear = date("Y", $beforeMonth); // 获取年份
        $beforeMonth = date("m", $beforeMonth); // 获取月份
        $beforePointsRanking = PointsRanking::query()->select('rank','points')->where('year', $beforeYear)->where('month', $beforeMonth)->where('user_id', $user['id'])->where('deleted', 0)->first();
        if($result['rank'] > $beforePointsRanking['rank'])
        {
            $result['rank_trend'] = 1;      //增长
        }elseif($result['rank'] < $beforePointsRanking['rank']){
            $result['rank_trend'] = 2;      //下降
        }
        if($result['points'] > $beforePointsRanking['points'])
        {
            $result['points_trend'] = 1;
        }elseif($result['points'] < $beforePointsRanking['points']){
            $result['points_trend'] = 2;
        }
        $beforeFans = DouyinData::query()->where('user_id', $user['id'])->where('year', $beforeYear)->where('month', $beforeMonth)->where('deleted', 0)->sum('fans_growth');
        $beforeVolume = DouyinData::query()->where('user_id', $user['id'])->where('year', $beforeYear)->where('month', $beforeMonth)->where('deleted', 0)->sum('volume');
        if($result['fans'] > $beforeFans)
        {
            $result['fans_trend'] = 1;      //增长
        }elseif($result['fans'] < $beforeFans){
            $result['fans_trend'] = 2;      //下降
        }
        if($result['volume'] > $beforeVolume)
        {
            $result['volume_trend'] = 1;
        }elseif($result['volume'] < $beforeVolume){
            $result['volume_trend'] = 2;
        }


        $result['month'] = $month;
        return $result;
    }

    public function getUser()
    {
        $user = auth_user();

        $result['avatar'] = $user['avatar'];
        $result['nickname'] = $user['nickname'];
        $result['id'] = $user['id'];
        return $result;
    }

    public function getUserInfo()
    {
        $user = auth_user();
        $userInfo = User::query()->select('id','avatar','nickname','birthday','gender','city','signature','wechat','qq','phone','steam','official_server_id','has_partner_privilege_official','test_server_id','has_partner_privilege_test','platform_name','platform_nickname','platform_homepage_link')->where('id', $user['id'])->first();

        //需求变更后前端不变，接口此处合并主平台信息
        $userPlatform = UserPlatform::query()->with('platform')->where('user_id', $user['id'])->where('status', 1)->where('deleted', 0)->get()->toArray();
        if($userInfo['platform_nickname'])
        {
            $mainPlatform = [
                'platform_nickname'=>$userInfo['platform_nickname'],
                'homepage_link'=>$userInfo['platform_homepage_link'],
                'platform'=>[
                    'name' => $userInfo['platform_name'],
                ]
            ];
            array_unshift($userPlatform, $mainPlatform);
        }

        return ['user'=>$userInfo, 'user_platform'=>$userPlatform];
    }

    public function subUserInfo(array $params)
    {
        $user = auth_user();
        $userData = User::query()->where('id', $user['id'])->first();

        //调整为仅可修改头像、签名
        $data['avatar'] = $params['avatar'];
        // $data['nickname'] = $params['nickname'];
        // $data['birthday'] = $params['birthday'];
        // $data['gender'] = $params['gender'];
        // $data['city'] = $params['city'];
        // $data['province_id'] = $params['province_id'];
        // $data['city_id'] = $params['city_id'];
        $data['signature'] = $params['signature'];
        // $data['wechat'] = $params['wechat'];
        // $data['qq'] = $params['qq'];
        // $data['phone'] = $params['phone'];
        // $data['steam'] = $params['steam'];
        // $data['official_server_id'] = $params['official_server_id'];
        // $data['has_partner_privilege_official'] = $params['has_partner_privilege_official'];
        // $data['test_server_id'] = $params['test_server_id'];
        // $data['has_partner_privilege_test'] = $params['has_partner_privilege_test'];

        User::query()->where('id', $user['id'])->update($data);

        return $userData;           //目前直接返回全部用户数据，和前端沟通后确认需要字段
    }

    public function subPlatformInfo(array $params)
    {
        $user = auth_user();

        $data['platform_1'] = $params['platform_1'];
        $data['platform_nickname_1'] = $params['platform_nickname_1'];
        $data['homepage_link_1'] = $params['homepage_link_1'];
        $data['platform_2'] = $params['platform_2'];
        $data['platform_nickname_2'] = $params['platform_nickname_2'];
        $data['homepage_link_2'] = $params['homepage_link_2'];

        User::query()->where('id', $user['id'])->update($data);

        return [];
    }

    public function myWallet(array $params)
    {
        $user = auth_user();

        $user = User::query()->select('id','star_currency','balance')->where('id', $user['id'])->first();       //重新获取用户信息

        $model = AccountRecord::query()->select('created_at','category','type','detail','star_currency','star_currency_balance','amount','balance','status')->where('user_id', $user['id'])->where('category', $params['category']);
        $list = $this->usePage($model)->toArray();

        //前端取值amount、balance即可
        if(!empty($list))
        {
            $statusArr = ['待处理','已处理'];
            foreach($list['data'] as $key=>$val)
            {
                if($params['category']=='star_currency')
                {
                    $list['data'][$key]['amount'] = $val['star_currency'];
                    $list['data'][$key]['balance'] = $val['star_currency_balance'];
                }
                $list['data'][$key]['status'] = $statusArr[$val['status']];
            }
        }

        return ['user'=>$user, 'list'=>$list];
    }

    public function withdrawal(array $params)
    {
        $user = auth_user();
        $accountRecord = AccountRecord::query()->where('user_id', $user['id'])->orderBy('id', 'DESC')->first();
        $createdAt = $accountRecord->created_at->format('Y-m-d H:i:s');
        if($accountRecord)
        {
            $m1 = date('Ym', strtotime($createdAt));
            $m2 = date('Ym');
            if($m1 == $m2){
                throw new ApiException(ErrorCode::WARNING, '每月最多提现一次');
            }
        }

        if (!validate_amount($params['amount'])) {
            throw new ApiException(ErrorCode::WARNING, '输入金额有误');
        }

        $userInfo = User::query()->select('balance')->where('id', $user['id'])->where('status', 1)->where('deleted', 0)->first();
        if($userInfo['balance'] < $params['amount'])
        {
            throw new ApiException(ErrorCode::WARNING, '余额不足');
        }

        $balance = $userInfo['balance'] - $params['amount'];

        $recordData['user_id'] = $user['id'];
        $recordData['category'] = 'withdrawal';
        $recordData['type'] = 'expense';      //支出
        $recordData['detail'] = '提现'.$params['amount'];
        $recordData['amount'] = $params['amount'];
        $recordData['balance'] = $balance;
        $recordData['realname'] = $params['realname'];
        $recordData['alipay_account'] = $params['alipay_account'];
        Db::beginTransaction();
        try{
            
            User::query()->where('id', $user['id'])->update(['balance' => $balance]);
            AccountRecord::query()->insert($recordData);

            Db::commit();
        } catch(\Throwable $e){
            Db::rollBack();
            throw new ApiException(ErrorCode::ERROR, $e->getMessage());
        }

        return [];
    }

    public function myOrder(array $params)
    {
        $user = auth_user();

        $where['user_id'] = $user['id'];
        if (!empty($params['order_no'])) {
            $where['order_no'] = $params['order_no'];
        }
        if (!empty($params['status'])) {
            $where['status'] = $params['status'];
        }
        $model = UserOrder::query()->with('goods')->where($where);
        $list = $this->usePage($model)->toArray();

        return $list;
    }

    public function getPlatform()
    {
        $list = Platform::query()->where('status', 1)->where('deleted', 0)->get()->toArray();
        foreach($list as $key=>$val)
        {
            $list[$key]['logo'] = env('HTTP_HOST').$val['logo'];
        }
        return $list;
    }

    public function subUserData(array $params)
    {
        $user = auth_user();

        $lastMonthYear = get_last_month_year();
        $year = $lastMonthYear['year'];
        $month = $lastMonthYear['month'];

        $fileUrl = str_replace(env('HTTP_HOST'), '', $params['file_url']);
        $fullPath = BASE_PATH.$fileUrl;

        if($params['platform_id'] == 1)     //抖音
        {
            $spreadsheet = IOFactory::load($fullPath);

            $worksheet = $spreadsheet->getActiveSheet();
            $highestColumn = $worksheet->getHighestColumn();
            $columnCount = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
    
            if($columnCount != 11)
            {
                throw new ApiException(ErrorCode::WARNING, '文件数据不正确');
            }

            $douyinData = DouyinData::query()->select('id')->where('user_id', $user['id'])->where('type', $params['type'])->where('year', $year)->where('month', $month)->where('deleted', 0)->first();
            if($douyinData)
            {
                // DouyinData::query()->select('id')->where('user_id', $user['id'])->where('type', $params['type'])->where('year', $year)->where('month', $month)->where('deleted', 0)->delete();
                throw new ApiException(ErrorCode::WARNING, '数据已上传');
            }
    
            $res = $spreadsheet->getActiveSheet()->toArray();

            //检查文件模板
            $title = [
                '作品名称',
                '发布时间',
                '审核状态',
                '播放量',
                '点赞量',
                '分享量',
                '评论量',
                '主页访问量',
                '粉丝增量',
                '完播率',
                '平均播放时长',
            ];
            if($res[0] != $title)
            {
                throw new ApiException(ErrorCode::WARNING, '文件格式不正确');
            }

            unset($res[0]);
            foreach($res as $val)
            {
                $data = [];

                if(!empty($user['id'])) $data['user_id'] = $user['id'];
                if(!empty($params['type'])) $data['type'] = $params['type'];
                if(!empty($year)) $data['year'] = $year;
                if(!empty($month)) $data['month'] = $month;
                if(!empty($val[0])) $data['title'] = $val[0];
                if(!empty($val[1])) $data['release_time'] = $val[1];
                if(!empty($val[2])) $data['review_status'] = $val[2];
                if(!empty($val[3])) $data['volume'] = $val[3];
                if(!empty($val[4])) $data['likes'] = $val[4];
                if(!empty($val[5])) $data['share_volume'] = $val[5];
                if(!empty($val[6])) $data['comment_volume'] = $val[6];
                if(!empty($val[7])) $data['homepage_visits'] = $val[7];
                if(!empty($val[8])) $data['fans_growth'] = $val[8];
                if(!empty($val[9])) $data['completion_rate'] = $val[9];
                if(!empty($val[10])) $data['average_duration'] = $val[10];

                DouyinData::query()->insert($data);
            }
        }else{
            throw new ApiException(ErrorCode::WARNING, '该平台数据未支持');
        }

        return [];
    }

    public function subWorkOrder(array $params)
    {
        $user = auth_user();
        $data['user_id'] = $user['id'];
        $data['type'] = $params['type'];
        $data['content'] = $params['content'];
        WorkOrder::query()->insert($data);
    }

    public function pointsRule()
    {
        $user = auth_user();
        
        $ruleArr = config('points_rule');

        return $ruleArr[$user['level']];
    }
}